﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using Icinetic.FeedCategorySample.CrossCutting;
using Icinetic.FeedCategorySample.Services.Exceptions;
using Windows.Storage;
using Windows.Storage.Streams;

namespace Icinetic.FeedCategorySample.Services.Providers
{
    public class TemporalImageStorageProvider
    {
        private static string temporalStorageFolderName = "cache";

        public static async Task<string> StoreImage(String imageRss)
        {
            return await SaveImageFile(imageRss);
        }
               
        public static async Task<StorageFolder> GetTemporalStorageFolder()
        {
            StorageFolder folder = null;

            try
            {
                Windows.Storage.StorageFolder appData = Windows.Storage.ApplicationData.Current.LocalFolder;

                if (!await appData.FolderExistsAsync(temporalStorageFolderName))
                    folder = await appData.CreateFolderAsync(temporalStorageFolderName, CreationCollisionOption.ReplaceExisting);
                else
                    folder = await appData.GetFolderAsync(temporalStorageFolderName);
            }
            catch(Exception ex)
            {
                LoggingService.Log(ex);
            }

            return folder;
        }

        private static async Task<string> SaveImageFile(string imageRss)
        {
            bool succeeded = false;
            string image = "";
            string baseFileName = imageRss.Replace("http://", "").Replace("/", "-").Replace(" ", "-");

            // Get image's URL
            string url = imageRss;
            // Get image's cache file name
            string completeFileName = baseFileName;

            if (await ExistsFile(completeFileName))
                succeeded = true;
            else
                succeeded = await SaveFileFromUrl(url, completeFileName);

            // Update changes (to persist new local storaged files)
            if (succeeded)
            {
                image = completeFileName;
            }

            return image;
        }

        private static async Task<bool> ExistsFile(string cacheFileName)
        {
            StorageFolder cacheFolder = await GetTemporalStorageFolder();
            return await cacheFolder.FileExistsAsync(cacheFileName);
        }

        private static async Task<bool> SaveFileFromUrl(string uri, string fileName)
        {
            bool succeeded = false;

            try
            {
                HttpClient client = new HttpClient();
                byte[] imageData = await client.GetByteArrayAsync(uri);

                StorageFolder cacheFolder = await GetTemporalStorageFolder();
                StorageFile file = await cacheFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);
                IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);
                IOutputStream outputStream = stream.GetOutputStreamAt(0);

                DataWriter writer = new DataWriter(outputStream);
                writer.WriteBytes(imageData);

                await writer.StoreAsync();
                await writer.FlushAsync();

                succeeded = true;
            }
            catch (Exception)
            {
                throw new ConnectionException();
            }

            return succeeded;
        }
    }
}
